package com.itboye.ihomebank.home;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.uploadmultipleimage.MultipartRequest;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.CameraPopupWindow;
import com.itboye.ihomebank.util.SPUtils;

/**
 * 实名认证
 * 
 */
public class ActivityRealName extends BaseOtherActivity implements Observer {
	private ImageView close_icon;// 返回图片
	private TextView add_shap_title_tv;// 标题
	private EditText real_name;// 真实姓名
	private EditText real_code;// 身份证号
	private TextView real_tijiao;// 提交

	private UserPresenter userPresenter;

	private String uid;// id

	private String realname;// 真实姓名
	private String ibnumber;// 身份证号
	private String code;// 验证码

	ImageView real_img01, real_img02;

	TextView real_img_send;// 提交照片

	CameraPopupWindow mCameraPopupWindow;

	/** 身份证正面的选择 */
	private String localSelectPath01;
	/** 身份证背面的选择 */
	private String localSelectPath02;

	private String fileName01;
	private String fileName02;
	private String type;

	/** 使用相机拍照（正面） */
	private static final int REAL_PHONE = 1;
	/** 使用相机拍照（背面） */
	private static final int REAL_PHONE_TWO = 3;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.close_icon:
			finish();
			break;

		case R.id.real_tijiao:// 提交认证
			realname = real_name.getText().toString();
			ibnumber = real_code.getText().toString();
			if (TextUtils.isEmpty(real_name.getText())) {
				ByAlert.alert("请输入真实姓名");
				return;
			}
			if (TextUtils.isEmpty(real_code.getText())) {
				ByAlert.alert("请输入身份证号");
				return;
			}
			userPresenter = new UserPresenter(this);
			userPresenter.getRealName(uid, realname, ibnumber, code);
			break;

		case R.id.real_img01:// 添加身份证正面照片
			type = "zheng";
			mCameraPopupWindow = new CameraPopupWindow(this, onclicklister01);
			mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;

		case R.id.real_img02:// 添加身份证背面照片
			type = "fan";
			mCameraPopupWindow = new CameraPopupWindow(this, onclicklister01);
			mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.real_img_send:// 提交图片
			// String[]
			// img={localSelectPath01,localSelectPath02,fileName01,fileName02};
			String[] img = { localSelectPath01, localSelectPath02 };
			// UploadImagesMore.getInstance().execute(img, "ID", this, null);
			// UploadImage.getInstance().execute(img,"ID", this,null);
			String url = "http://api.ihomebank.com/public/index.php/file/upload?client_id=by565fa4facdb191";
			Map<String, String> params = new HashMap<String, String>();
			params.put("uid", uid);
			params.put("type", "ID");
			File f1 = null;
			File f2 = null;
			if (localSelectPath01 == null || localSelectPath02 == null) {
				ByAlert.alert("请先选择有效图片");
				return;
			}
			f1 = new File(localSelectPath01);
			f2 = new File(localSelectPath02);
			List<File> f = new ArrayList<File>();
			f.add(f1);
			f.add(f2);
			MultipartRequest request = new MultipartRequest(url,
					new Response.Listener<String>() {

						@Override
						public void onResponse(String response) {
							Toast.makeText(getApplicationContext(),
									"uploadSuccess,response = " + response,
									Toast.LENGTH_SHORT).show();
							Log.i("w", "success,response = " + response);
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							Toast.makeText(
									getApplicationContext(),
									"uploadError,response = "
											+ error.getMessage(),
									Toast.LENGTH_SHORT).show();
							Log.i("w", "error,response = " + error.getMessage());
						}
					}, "image[]", f, params); // 注意这个key必须是f_file[],后面的[]不能少
			MyApplcation.addRequest(request);
			break;

		default:
			break;
		}
	}

	private String picture_name;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REAL_PHONE:// 相机
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					Log.i("TestFile",
							"SD card is not avaiable/writeable right now.");
					return;
				}
				picture_name = android.text.format.DateFormat.format(
						"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
						+ ".jpg";
				Bundle bundle = data.getExtras();
				Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
				// SavePicInLocal(bitmap);
				FileOutputStream b = null;
				File file = new File("/sdcard/Image/");
				file.mkdirs();// 创建文件夹
				fileName01 = "/sdcard/Image/" + picture_name;

				try {
					b = new FileOutputStream(fileName01);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				Bitmap bit = BitmapFactory.decodeFile(fileName01);
				if (type != null) {
					if (type.equals("zheng")) {
						localSelectPath01 = fileName01;
						real_img01.setImageBitmap(bit);
					} else {
						localSelectPath02 = fileName01;
						real_img02.setImageBitmap(bit);
					}
				}

				mCameraPopupWindow.dismiss();
				break;

			case REAL_PHONE_TWO:// 相册
				/**
				 * 当选择的图片不为空的话，在获取到图片的途径
				 */
				Uri selectedImage04 = data.getData();
				String innerUrl=getRealPathFromURI(selectedImage04);
				if (type != null) {
					if (type.equals("zheng")) {
						localSelectPath01 = innerUrl;
					} else {
						localSelectPath02 = innerUrl;
					}
				}

				Bitmap bt04 = BitmapFactory.decodeFile(innerUrl);
				if (type != null) {
					if (type.equals("zheng")) {
						real_img01.setImageBitmap(bt04); // 把图片显示在ImageView控件上

					} else {
						real_img02.setImageBitmap(bt04);
					}
				}
				mCameraPopupWindow.dismiss();
				break;

			default:
				break;
			}
		}

	}

	/**
	 * 该方法用于获取文件的真实路径从URI 从相机拍摄
	 */
	private String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	/**
	 * 正面
	 */
	private OnClickListener onclicklister01 = new OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.open_camera:
				/**
				 * 打开照相机
				 */
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent, REAL_PHONE);

				} else {
					Toast.makeText(ActivityRealName.this, "请确认已经插入SD卡", 2000)
							.show();
				}
				break;
			case R.id.pick_image:
				Intent intent2 = new Intent();
				intent2.setType("image/*");// 可选择图片视频
				// 修改为以下两句代码
				intent2.setAction(Intent.ACTION_PICK);
				intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
				startActivityForResult(intent2, REAL_PHONE_TWO);
				break;
			case R.id.img:
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_real_name;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		add_shap_title_tv.setText("实名认证");
		uid = (String) SPUtils.get(this, null, SPContants.USER_ID, "");

	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (!entity.getCode().equals(0)) {

				if (entity.getEventType() == UserPresenter.realName_success) {
					String bean = (String) entity.getData();
					if (bean != null) {
						ByAlert.alert("申请已经提交,等待审核中...");
						finish();
//						Intent intent = new Intent(this,
//								ActivityRealName_Two.class);
//						startActivity(intent);
					}

				}
				if (entity.getEventType() == UserPresenter.realName_fail) {
					ByAlert.alert("认证失败");
				}
			}
		}

	}
}
